<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Nodes extends AdminController {
	
	var $num_elements = 10;
		
	function Nodes() {
		parent::AdminController ();
		
		$this->load->model ( "Node_Model" , "Nodes" );
		
		$this->load->helper('language');
		$this->lang->load('admin');

		$this->load->helper('date');
		
		$this->load->library("CTypes");
		
		$num_elements = $this->settings->item("_admin_list_elements");
		if($num_elements != NULL){
			$this->num_elements = $num_elements;
		}
	}
	
	function index($type = NULL) {
		$this->load->model ( "Category_Model" , "Categories" );
		$this->load->model ( "Comment_Model" , "Comments" );
		$this->load->model ( "redux_auth/Users_Model", "Users");
		
		$this->load->library('pagination');
		
		$pag = $this->pagination->segment_value();
		if($pag == NULL){
			$pag = 0;			
		}
		
		$params = array(
			"status" 		=> "publish",
			"num_comments"	=> TRUE,
			"order"			=> array(
				"publish" => "desc"
			)
		);
		
		if(($type != NULL && $type != "page") || (isset($_GET['type']) && $_GET['type'] != -1)){
			if($type != NULL){
				$params['type'] = $type;
			} else{
				$params['type'] = $_GET['type'];
			}
			
		}
		
		if(isset($_GET['cat']) && $_GET['cat'] != -1){
			$params['categories'] = array();
			array_push($params['categories'], $_GET['cat']);
			$params['categories_childs'] = TRUE;
		}
		
		if(isset($_GET['tag'])){
			$params['tags'] = array();
			array_push($params['tags'], $_GET['tag']);
		}
		
		if(isset($_GET['status'])){
			$params['status'] = $_GET['status'];
		}
		$this->_addData("filter_status", $params['status']);
		
		if(isset($_GET['user'])){
			$params['user'] = $_GET['user'];
		}
		
		$params['start'] = $pag;
		$params['offset'] = $this->num_elements;
		
		//print_r($params);
		
		$totalNodes = $this->Nodes->getCount($params);
		/*$nodes = $this->Nodes->get($params, $pag, $this->num_nodes);
		
		$nodes_process = array();
		foreach($nodes as $node){
			$nodes_comments = $this->Comments->getCount(array(
				"node_id" 			=> $node->id,
				"comment_status"	=> "all"
			));
			
			$node->num_comments = $nodes_comments;
			
			array_push($nodes_process, $node);
		}*/
		$nodes_process = $this->Nodes->get($params);
		
		$elements_tmp = array();
		foreach($nodes_process as $el){
			$categories = $this->Nodes->getCategories($el->id);
			$tags = $this->Nodes->getTags($el->id);
			$user_created = $this->Users->getUserById($el->user_created);
			
			$el->categories = $categories;
			$el->tags = $tags;
			$el->user_created = $user_created;
			
			array_push($elements_tmp, $el);
		}
		
		$nodes_process = $elements_tmp;
		

		$config['base_url'] = "/admin/nodes/index/";
		$config['total_rows'] = $totalNodes;
		$config['per_page'] = $this->num_elements;
		
		$config['full_tag_open'] = '<div class="pagination">';
		$config['full_tag_close'] = '</div>';
		
		$config['num_tag_open'] = '<span class="number">';
		$config['num_tag_close'] = '</span>';
		
		$config['cur_tag_open'] = '<span class="number current">';
		$config['cur_tag_close'] = '</span>';
		
		$config['first_link'] = 'Inicio';
		$config['last_link'] = 'Último';
		$config['prev_link'] = '&lt; Ant';
		$config['next_link'] = 'Sig &gt;';

		$this->pagination->initialize($config);
		
		$this->_addData("nodes", $nodes_process);
		$this->_addData("totalNodes", $totalNodes);
		
		$params['status'] = "all";
		$this->_addData("nodes_all", $this->Nodes->getCount($params));
		
		$params['status'] = "publish";
		$this->_addData("nodes_publish", $this->Nodes->getCount($params));
		
		$params['status'] = "draft";
		$this->_addData("nodes_draft", $this->Nodes->getCount($params));
		
		$params['status'] = "future";
		$this->_addData("nodes_future", $this->Nodes->getCount($params));
		
		$params['status'] = "expire";
		$this->_addData("nodes_expire", $this->Nodes->getCount($params));
		
		$categories = $this->Categories->get(array("status" => "all", "num_nodes" => TRUE, "categories_childs" => TRUE));
		$this->_addData("categories", $categories);
		
		$types = $this->settings->item("content_types");
		$this->_addData("types", $types);

		$this->_render();
	}
	
	function add() {			
		$types = $this->ctypes->getTypes();		
		$this->_addData("types", $types);
		
		$this->_render();	
	}
	
	function edit($id = NULL){
		$this->_setPageView("nodes/proccess");
		
		if($id != NULL){
			$node = $this->Nodes->get(array('id' => $id, 'status' => 'all'));
			
			if($node != NULL){
				$this->proccess($node->type, $node->id);
			}
		}
	}
	
	function proccess($type = NULL, $id = NULL) {
		
		$referrer = $this->session->userdata("referrer");
		
		$types = $this->ctypes->getTypes();
		
		$this->_addData("types", $types);
		
		if($type != null){
			$this->load->helper("array");
			
			if( element($type, $types, NULL) != NULL){
				
				$this->_addData("type", $types[$type]);

				if( $this->ctypes->checkCorrectSave($type)){
					if($id != NULL){
						$node = $this->ctypes->save($type, $id);
					} else{
						$node = $this->ctypes->save($type);
					}
					
					if($node !== FALSE && $node != NULL){
						if($id != NULL){
							$this->_addFlashSuccess("Contenido editado correctamente");
						} else{
							$this->_addFlashSuccess("Contenido creado correctamente");
						}
						
						$action = $this->input->post("action");
						
						if($action == "saveexit"){
							
							if($referrer != NULL && strpos($referrer, "nodes/add") === FALSE){
								redirect($referrer);
							} else{
								redirect("admin/nodes");
							}
						} else{
							if($referrer != NULL){
								$this->session->set_flashdata("referrer", $referrer);
							}
							
							redirect("admin/nodes/proccess/" . $node->type . "/" . $node->id);
							
						}
						
						//redirect("admin/nodes");
					}
				} else{
					if($id != NULL){
						$form = $this->ctypes->view($type, $id);
					} else{
						$form = $this->ctypes->view($type);
					}
					
					
					if($form !== FALSE){
						$this->_addData("form", $form);
					}
				}
			} else{
				echo "NO encontrado $type";
			}
		}

		$this->_render();
	}

	function delete($type = NULL, $id = NULL) {
		
		if($type != NULL && $id != NULL){
			if($this->ctypes->get($type) !== FALSE){
				$node = $this->ctypes->delete($type, $id);
				
				if($node === FALSE){
					$this->_addFlashError("Ocurrio un error al eliminar el contenido");
				} else{				
					$this->_addFlashSuccess("Eliminado correctamente");
				}
			} else{
				$this->Nodes->delete($id);
				$this->_addFlashSuccess("Eliminado correctamente, aunque no se encontro el tipo de contenido");
			}
		} else{
			$this->_addFlashError("No se ha especificado tipo ni/o id");
		}
		
		redirect ( 'admin/nodes');
	}
	
	
	
	
	
	/*** COMENTARIOS ***/
	
	function comments_list(){
		$this->load->model ( "Comment_Model" , "Comments" );
		$this->load->library('pagination');
		
		$pag = $this->pagination->segment_value();
		if($pag == NULL){
			$pag = 0;			
		}
		
		$params = array(
			"status" 	=> "all"
		);
		
		if(isset($_GET['node'])){
			$params['node_id'] = $_GET['node'];
		}
		
		if(isset($_GET['user'])){
			$params['user'] = $_GET['user'];
		}
		
		if(isset($_GET['ip'])){
			$params['ip'] = $_GET['ip'];
		}
		
		if(isset($_GET['status'])){
			$params['status'] = $_GET['status'];
		}
		
		$total = $this->Comments->getCount($params);
		$comments = $this->Comments->get($params, $pag, $this->num_nodes);
		
		$comments_process = array();
		foreach($comments as $comment){
			$nodes_comments = $this->Comments->getCount(array(
				"node_id" 	=> $comment->node_id,
				"status"	=> "all"
			));
			
			$comment->node_num_comments = $nodes_comments;
			
			array_push($comments_process, $comment);
		}

		$config['base_url'] = "/admin/nodes/index/";
		$config['total_rows'] = $total;
		$config['per_page'] = $this->num_nodes;
		//$config['uri_segment'] = 4;
		
		$config['full_tag_open'] = '<div class="pagination">';
		$config['full_tag_close'] = '</div>';
		
		$config['num_tag_open'] = '<span class="number">';
		$config['num_tag_close'] = '</span>';
		
		$config['cur_tag_open'] = '<span class="number current">';
		$config['cur_tag_close'] = '</span>';
		
		$config['first_link'] = 'Inicio';
		$config['last_link'] = 'Último';
		$config['prev_link'] = '&lt; Ant';
		$config['next_link'] = 'Sig &gt;';

		$this->pagination->initialize($config);
		
		$this->_addData("comments", $comments);
		$this->_addData("total_comments", $total);

		$this->_render();
	}
	
	function comments_delete($id = NULL) {
		$this->load->model ( "Comment_Model" , "Comments" );
		if($id != null){
			$this->Comments->delete($id);
			$this->_addFlashSuccess("Comentario eliminado correctamente");
		}
		
		redirect ( $this->session->userdata("referrer"), 'refresh' );
	}
	
	function comments_edit($id = NULL) {
		$this->_setPageView("nodes/comments_form");	
		
		if($id != NULL){
			$this->_addData("id", $id);
			
			$this->load->model ( "Comment_Model" , "Comments" );
			$comment = $this->Comments->get(array("id" => $id, "status" => "all"));
			
			if($comment != NULL){
			
				$this->form_validation->set_rules('data', 'Comentario', 'required');
				
				if($comment->user_id == NULL || $comment->user_id == -1){
					$this->form_validation->set_rules('name', 'Nombre', 'required|trim');
					$this->form_validation->set_rules('email', 'Email', 'trim|valid_email');
					$this->form_validation->set_rules('url', 'Url', 'trim');
				}
		
				if ($this->form_validation->run() == TRUE){
					$fields = array(
						'id' 	=> $id,
						'data'	=> $this->input->post("data")
					);
					
					if($comment->user_id == NULL || $comment->user_id == -1){
						$fields['name'] = $this->input->post("name");
						$fields['email'] = $this->input->post("email");
						$fields['url'] = $this->input->post("url");
					}
					
					$this->Comments->update($fields);
					
					$this->_addFlashSuccess("Comentario modificado correctamente");
					
					$referrer = $this->session->userdata("referrer");
					if($referrer != NULL && $referrer != ""){
						redirect ($referrer, "refresh");
					} else{
						redirect("admin/nodes/comments_list", 'refresh');
					}
					
				} else{				
					$this->_addData("comment", $comment);
					
					$this->_render();
				}
			}
		}
		
	}
	



/*
$post = array(
  'comment_status' => [ 'closed' | 'open' ] // 'closed' no permite comentarios.
  'ID' => [ <post id> ] // únicamente si estamos actualizando un comentario.
  'menu_order' => [ <order> ] //Si es una nueva página, especifica el orden en el que debería aparecer
  'page_template => [ <template file> ] // Indica el template para la página.
  'ping_status' => [ ? ] // Activamos o desactivamos los pingbacks
  'pinged' => [ ? ] //?
  'post_author' => [ <user ID> ] //ID del usuario
  'post_category => [ array(<category id>, <...>) ] // Categorías del post.
  'post_content' => [ <the text of the post> ] // Contenido del post.
  'post_date' => [ Y-m-d H:i:s ] // Fecha de creación del post.
  'post_date_gmt' => [ Y-m-d H:i:s ] // Fecha de creación en GMT.
  'post_excerpt' => [ <an excerpt> ] // El resumen del post.
  'post_parent' => [ <post ID> ] // El post padre.
  'post_password' => [ ? ] // El password del post.
  'post_status' => [ 'draft' | 'publish' | 'pending' ] // Estado de la publicación
  'post_title' => [ <the title> ] // Título del post.
  'post_type' => [ 'post' | 'page' ] // Post o Página.
  'tags_input' => [ '<tag>, <tag>, <...>' ] // Tags asociados al post.
  'to_ping' => [ ? ] //?
);
// Insertamos el post
wp_insert_post( $post );
*/
	

}
?>
